<?php

/**
 * 获取模板主题列表
 * @param string $m 模块
 * @return array
 */
function get_theme_all($m = 'home') {
    $theme_list = array();
    $list = glob(APP_PATH . DS . $m . DS . 'view' . DS . '*', GLOB_ONLYDIR);
    foreach ($list as $v) {
        $theme_list[] = basename($v);
    }
    //debug($theme_list);
    return $theme_list;
}

/**
 * 用于设置模块的主题
 */
function set_module_theme($theme = 'default') {
    defined('MODULE_THEME') or define('MODULE_THEME', $theme);
}

/**
 * 加载字段显示
 */
function admin_show_field($field, $type = 'open') {
    if ($type == 'open') {
        if ($field == '1') {
            echo '<span class="label label-success radius">已启用</span>';
        } else {
            echo '<span class="label label-default radius">已禁用</span>';
        }
    } else if ($type == 'is') {
        if ($field == 1) {
            echo '是';
        } else {
            echo '否';
        }
    }
}

/**
 * 更新状态 1开启
 */
function update_status($url, $table_name, $id_name, $id_value, $field, $status) {
    if ($status == 1) {
        echo ' <img src="/static/common/img/yes.png" width="16" height="16" alt=""
  onclick=\'changeTableVal("' . $url . '","' . $table_name . '", "' . $id_name . '", "' . $id_value . '", "' . $field . '", this)\' />';
    } else {
        echo '<img src="/static/common/img/cancel.png" width="16" height="16" alt=""
  onclick=\'changeTableVal("' . $url . '","' . $table_name . '", "' . $id_name . '", "' . $id_value . '", "' . $field . '", this)\' />';
    }
}

/**
 * 前台头部菜单
 *  */
function home_show_menu() {
    $list = db('category')->field('catid,catname,arrchildid,pclink,type')->where(array('parentid' => 0, 'disabled' => 1))->order('sort')->limit(20)->select();
    $catid = ticky\request::get('catid', 0);
    $current = ' ';
    if (!isset($catid)) {
        $current = 'class="current"';
    }
    $str = ' <li><a ' . $current . ' href="/">首页</a></li>';
    foreach ($list as $val) {
        $catname = $val["catname"];
        $pclink = $val["pclink"];
        if (isset($catid) && $val['catid'] == $catid) {
            $current = 'class="current"';
        } else {
            $current = '';
        }
        $str .= "<li>";
        $str .= "<a href='{$pclink}' {$current}>{$catname}</a>";
        $r = get_childcat($val['catid']);
        if (count($r) > 0) {
            $str .= '<ul class="sub_nav">';
            foreach ($r as $v) {
                $str .= '<li><a href="' . $v["pclink"] . '">' . $v["catname"] . '</a></li>';
            }
            $str .= '</ul>';
        }
        $str .= "</li>";
    }
    return $str;
}

/**
 * 模板选择
 *
 * @param $style  风格
 * @param $pre 模板前缀
 */
function select_template($style, $pre = '') {
    $files = glob(APP_PATH . DS . 'home' . DS . 'view' . DS . 'default' . DS . $pre . '*.html');
    $files = @array_map('basename', $files);
    $templates = array();
    if (is_array($files)) {
        foreach ($files as $file) {
            $key = substr($file, 0, -5);
            $templates[$key] = $file;
        }
    }
    $tem_style = APP_PATH . DS . 'home' . DS . 'view' . DS . 'default' . DS . 'config.php';
    if (is_file($tem_style)) {
        $templets = require($tem_style);
        return array_merge($templates, $templets[$style]);
    } else {
        return $templates;
    }
}

/**
 * 内容模型 显示树形下拉框.
 * @param string $roleid  选中id.
 * @return string.
 */
function showsitemodel($modelid = '', $selname = 'modelid', $change = false) {
    $siteid = get_siteid();
    $s = 'selected="selected"';
    $onchange = $change ? 'onchange="change_model()"' : "";
    $str = '<select id="' . $selname . '" name="' . $selname . '"  ' . $onchange . ' class="form-control" style="width: 110px;"><option  value="0">内容模型</option>';
    $list = db('model')->where(array('disabled' => 1, 'type' => 0, 'siteid' => $siteid))->order('modelid ASC')->select();
    foreach ($list as $val) {
        $act = trim($val['modelid']) == trim($modelid) ? $s : "";
        $str .= '<option ' . $act . ' value="' . $val['modelid'] . '">' . $val['name'] . '</option>';
    }
    $str .= '</select>';
    return $str;
}

function getsitemodel() {
    $modelinfo = db('model')->where(array('disabled' => 1, 'siteid' => get_siteid()))->order('modelid ASC')->select();
    $modelarr = array();
    foreach ($modelinfo as $val) {
        $modelarr[$val['modelid']] = $val['name'];
    }
    return $modelarr;
}

/**
 * 获取栏目的select
 * select_category('catid', $catid, '内容分类', 0, '', true, true, $modelid);
 * @param $name     select的名称
 * @param $value    选中的id，用于修改
 * @param $root     顶级分类名称
 * @param $member_publish 是否仅显示投稿栏目
 * @param $attribute 外加属性
 * @param $parent_disabled 是否禁父级栏目
 * @param $disabled 是否禁单页和外部链接
 * @param $modelid  modelid
 * @return string
 */
function select_category($name = "parentid", $value = "0", $root = "", $member_publish = 0, $attribute = '', $parent_disabled = true, $disabled = true, $modelid = 0) {
    if ($root == '') {
        $root = "≡ 作为一级栏目 ≡";
    }
    $categorys = array();
    $html = '<select id="select" name="' . $name . '"  ' . $attribute . ' class="form-control" style="width: 200px;">';
    $html .= '<option value="0">' . $root . '</option>';
    if ($member_publish) {
        $where = array('member_publish' => 1, 'siteid' => get_siteid());
        $data = db('category')->field('catid,arrparentid')->where($where)->select();
        $arr = array();
        foreach ($data as $val) {
            $arr[$val['catid']] = $val['arrparentid'];
        }
        $arr = array_merge(array_unique(explode(',', join(',', $arr))), array_keys($arr));
    }
    $where = array();
    $where['siteid'] = get_siteid();
    if ($modelid) {
        $where['modelid'] = $modelid;
    }
    $tree = new \ticky\tree();
    $data = db('category')->field('catid AS id,catname AS name,parentid,arrchildid,type')->where($where)->select();
    foreach ($data as $val) {
        if ($member_publish) {
            if (!in_array($val['id'], $arr)) {
                continue;
            }
        }
        $val['html_disabled'] = 0;
        if ($parent_disabled) {
            if ($val['id'] != $val['arrchildid']) {
                $val['html_disabled'] = 1;
            }
        }
        if ($disabled) {
            if ($val['type'] != 0) {
                $val['html_disabled'] = 1;
            }
        }
        $categorys[$val['id']] = $val;
    }
    $tree->init($categorys);
    $tree->icon = array('&nbsp;&nbsp;&nbsp;│ ', '&nbsp;&nbsp;&nbsp;├─ ', '&nbsp;&nbsp;&nbsp;└─ ');
    $tree->nbsp = '&nbsp;&nbsp;&nbsp;';
    $html .= $tree->get_tree_category(0, "<option value='\$id' \$selected>\$spacer\$name</option>", "<optgroup label='\$spacer \$name'></optgroup>", $value);
    $html .= '</select>';
    return $html;
}

/**
 * 获取栏目信息
 *
 * @param  int $catid
 * @param  string $parameter
 * @return array or string
 */
function get_category($catid = '', $parameter = '') {
    if (!$categoryinfo = cache('categoryinfo')) {
        $data = db('category')->order('sort ASC, catid ASC')->select();
        $categoryinfo = array();
        foreach ($data as $val) {
            $categoryinfo[$val['catid']] = $val;
        }
        cache('categoryinfo', $categoryinfo);
    }
    if ($catid) {
        if (empty($parameter))
            return array_key_exists($catid, $categoryinfo) ? $categoryinfo[$catid] : array();
        else
            return array_key_exists($catid, $categoryinfo) ? $categoryinfo[$catid][$parameter] : '';
    }else {
        return $categoryinfo;
    }
}

/**
 * 根据栏目ID获取子栏目信息
 *
 * @param  int $catid
 * @return array
 */
function get_childcat($catid) {
    $catid = intval($catid);
    $data = get_category();
    $r = array();
    foreach ($data as $v) {
        if ($v['parentid'] == $catid)
            $r[] = $v;
    }
    return $r;
}

/**
 * 根据栏目ID获取栏目名称
 *
 * @param  int $catid
 * @return string
 */
function get_catname($catid) {
    $catid = intval($catid);
    $data = get_category($catid);
    if (!$data)
        return '';
    return $data['catname'];
}

/**
 * 根据栏目ID获取当前位置
 *
 * @param  int $catid
 * @param  bool $self 是否包含本身 0为不包含
 * @param  string $symbol 栏目间隔符
 * @return string
 */
function get_location($catid, $self = true, $symbol = '') {
    $catid = intval($catid);
    $catdata = get_category();
    $data = explode(',', $catdata[$catid]['arrparentid']);
    $str = '<li><a href="' . SITE_URL . '"><i class="fa fa-home fa-fw"></i>首页</a></li>';
    foreach ($data as $v) {
        if ($v)
            $str .= $symbol . '<li><a href="' . $catdata[$v]['pclink'] . '" title="' . $catdata[$v]['catname'] . '">' . $catdata[$v]['catname'] . '</a></li>';
    }
    if ($self)
        $str .= $symbol . '<li><a href="' . $catdata[$catid]['pclink'] . '" title="' . $catdata[$catid]['catname'] . '">' . $catdata[$catid]['catname'] . '</a></li>';
    return $str;
}

/**
 * 角色 显示树形下拉框.
 * @param string $roleid  选中id.
 * @return string.
 */
function showselectrole($roleid = '', $selname = 'roleid') {
    $s = 'selected="selected"';
    $str = '<select id="' . $selname . '" name="' . $selname . '" class="form-control" style="width: 200px;"><option  value="0">=角色=</option>';
    $list = db('auth_role')->select();
    foreach ($list as $val) {
        $act = trim($val['roleid']) == trim($roleid) ? $s : "";
        $str .= '<option ' . $act . ' value="' . $val['roleid'] . '">' . $val['title'] . '</option>';
    }
    $str .= '</select>';
    return $str;
}

/**
 * 用户组 显示树形下拉框.
 * @param string $roleid  选中id.
 * @return string.
 */
function showselectusergroup($groupid = '', $selname = 'groupid') {
    $s = 'selected="selected"';
    $str = '<select id="' . $selname . '" name="' . $selname . '" class="form-control" style="width: 110px;"><option  value="0">用户组</option>';
    $list = db('member_group')->select();
    foreach ($list as $val) {
        $act = trim($val['groupid']) == trim($groupid) ? $s : "";
        $str .= '<option ' . $act . ' value="' . $val['groupid'] . '">' . $val['name'] . '</option>';
    }
    $str .= '</select>';
    return $str;
}

/**
 * 获取组别信息
 *
 * @param  int $groupid
 * @return array
 */
function get_groupinfo($groupid = '') {
    if (!$member_group = cache('member_group')) {
        $data = db('member_group')->select();
        $member_group = array();
        foreach ($data as $val) {
            $member_group[$val['groupid']] = $val;
        }
        cache('member_group', $member_group);
    }
    if ($groupid) {
        return array_key_exists($groupid, $member_group) ? $member_group[$groupid] : array();
    } else {
        return $member_group;
    }
}

/**
 * 根据组别ID获取组别名称
 *
 * @param  int $groupid
 * @return string
 */
function get_groupname($groupid) {
    $groupid = intval($groupid);
    $data = get_groupinfo($groupid);
    if (!$data)
        return '';
    return $data['name'];
}

/**
 * 获取模型信息
 * @param $typeall    0只包含内容模型，1全部模型
 * @return array
 */
function get_modelinfo($typeall = 0) {
    $where = array('disabled' => 1);
    if ($typeall == 0) {
        $filename = 'modelinfo';
        $where['type'] = 0;
    } else {
        $filename = 'modelinfo_all';
    }
    if (!$modelarr = cache($filename)) {
        $data = db('model')->where($where)->order('modelid ASC')->select();
        $modelarr = array();
        foreach ($data as $val) {
            $modelarr[$val['modelid']] = $val;
        }
        cache($filename, $modelarr);
    }
    return $modelarr;
}

/**
 * 根据模型ID获取model信息
 *
 * @param  int $modelid
 * @param  bool $parameter 获取键名称
 * @return string
 */
function get_model($modelid, $parameter = 'tablename') {
    $modelinfo = get_modelinfo();
    if (!isset($modelinfo[$modelid]))
        return false;
    return $modelinfo[$modelid][$parameter];
}

/**
 * 获取站点HTML
 *
 * @param  int $catid
 * @return string
 */
function get_sitehtml() {
    $data = get_siteinfo();
    $str = '';
    foreach ($data as $val) {
        $str .= '  <li><a href="javascript:;" data-val="' . $val['siteid'] . '" data-url="' . $val['domain'] . '" title="' . $val['name'] . '">' . $val['name'] . '</a></li>';
    }
    return $str;
}

/**
 * 获取站点信息
 *
 * @param  int $siteid
 * @return array
 */
function get_siteinfo($siteid = '') {
    if (!$site = cache('site')) {
        $data = db('site')->select();
        $site = array();
        foreach ($data as $val) {
            $site[$val['siteid']] = $val;
        }
        cache('site', $site);
    }
    if ($siteid) {
        return array_key_exists($siteid, $site) ? $site[$siteid] : array();
    } else {
        return $site;
    }
}

/**
 * 获取当前的站点ID
 */
function get_siteid() {
    static $siteid;
    if (defined('IN_ADMIN')) {
        $siteid = !isset($_COOKIE['ticky_tickysite']) ? 1 : $_COOKIE['ticky_tickysite'];
    } else {
        if (!empty($siteid))
            return $siteid;
        $data = get_siteinfo();
        if (!is_array($data))
            return '1';
        foreach ($data as $v) {
            if (empty($v['domain']) || $v['domain'] == '/')
                $siteid = $v['siteid'];
        }
    }
    if (empty($siteid))
        $siteid = 1;
    return $siteid;
}

/**
 * 获取用户详细信息
 */
function get_memberinfo($uid) {
    $member = db('member')->where(array('uid' => $uid))->find();
    $member_profile = db('member_profile')->where(array('uid' => $uid))->find();
    if ($member_profile) {
        $item = array_merge($member, $member_profile);
    } else {
        $item = $member;
    }
    return $item;
}

/* * **********************end ************************* */

/**
 * 获取系统配置信息
 * @param $key 键值，可为空，为空获取整个数组
 * @return array|string
 */
function get_config($skey = '') {
    if (!$configs = cache('setting')) {
        $serialized = array('register', 'mail', 'ftp');
        $data = db('setting')->select();
        $configs = array();
        foreach ($data as $cnf) {
            if (in_array($cnf['skey'], $serialized)) {
                $cnf['svalue'] = unserialize($cnf['svalue']);
                foreach ($cnf['svalue'] as $key => $val) {
                    if (is_array($val)) {
                        foreach ($val as $k => $v) {
                            $cnf['svalue'][$key][$k] = max(0, intval($v));
                        }
                    }
                }
            }
            $configs[$cnf['skey']] = $cnf['svalue'];
        }
        cache('setting', $configs);
    }
    if (!$skey) {
        return $configs;
    } else {
        return array_key_exists($skey, $configs) ? $configs[$skey] : '';
    }
}

function set_count($skey, $num) {
    $where = ' `svalue`=`svalue`+' . $num . ' ';
    db('setting')->update($where, array('skey' => $skey));
}

/**
 * 判断当前登录永丰虎密码是否是默认密码
 * @return bool
 */
function is_default_password() {
    $user = \application\common\models\member_model::get_user_info();
    $default_password = authcode(get_config('default_password'), 'ENCODE');
    if ($default_password == $user['password']) {
        return true;
    } else {
        return false;
    }
}

/**
 * 词语过滤
 * @param $message - 词语过滤文本
 * @return 成功返回原始文本，否则提示错误或被替换
 */
function censor($message, $modword = NULL, $return = FALSE) {
    $censor = \application\common\models\newsword::instance();
    $censor->check($message, $modword);
    if ($censor->modbanned()) {
        $wordbanned = implode(', ', $censor->words_found);
        if ($return) {
            return array('message' => array('wordbanned' => $wordbanned));
        }
    }
    return $message;
}

function parse_related_link($content, $extent) {
    return \application\common\models\newskey::parse_related_link($content, $extent);
}

/**
 * 检查用户名是否符合规定
 * 登录名;4至16位，以字母开头，字母，数字，减号，下划线
 * @param STRING $username 要检查的用户名
 * @return 	TRUE or FALSE
 */
function is_username($username) {
    $strlen = dstrlen($username);
    if (is_badword($username) || !preg_match("/^[a-zA-Z]([-_a-zA-Z0-9]{4,16})+$/", $username)) {
        return false;
    } elseif (20 < $strlen || $strlen < 4) {
        return false;
    }
    return true;
}

/**
 * 检查密码长度是否符合规定
 * 密码:6到20位（字母，数字，下划线，减号）
 * @param STRING $password
 * @return 	TRUE or FALSE
 */
function is_password($password) {
    $strlen = dstrlen($password);
    if (!preg_match("/^[a-zA-Z0-9_-]{6,20}$/", $password)) {
        return false;
    } elseif (20 < $strlen || $strlen < 6) {
        return false;
    }
    return true;
}

/**
 * 显示后台菜单
 */
function show_menu() {
    if (!$menu_string = cache('menu_string_' . session('roleid'))) {
        $menu_list = get_menu();
        $menu_string = '';
        $ac = '';
        foreach ($menu_list as $key => $val) {
            if (empty($val['icon'])) {
                $val['icon'] = 'fa-square-o';
            }
            if (MODULE_NAME == $val['m']) {
                $ac = 'class="active"';
            }
            $menu_string .= '<li ' . $ac . '><a href="#"><i class="fa ' . $val['icon'] . ' fa-fw"></i> ' . $val['name'] . '<span class="fa arrow"></span></a>'
                    . ' <ul class="nav nav-second-level">';
            foreach ($val['child'] as $v) {
                if (empty($v['icon'])) {
                    $v['icon'] = 'fa-square-o';
                }
                $fun = 'onclick="breadcrumb(\'' . $v['m'] . '\',\'' . $v['c'] . '\',\'' . $v['a'] . '\')"';
                $menu_string .= '<li><a target="main" ' . $fun . '  href="' . url($v['m'] . '/' . $v['c'] . '/' . $v['a'], $v['data']) . '"><i class="fa ' . $v['icon'] . '  fa-fw"></i>' . $v['name'] . '</a></li>';
            }
            $menu_string .= ' </ul></li>';
        }
        cache('menu_string_' . session('roleid'), $menu_string);
    }
    return $menu_string;
}

/**
 * 获取菜单
 */
function get_menu() {
    $menu_list = db('menu')->field('`id`,`name`,`m`,`c`,`a`,`data`,icon')->where(array('parentid' => '0', 'display' => '1'))->order('listorder ASC')->limit('20')->select();
    $uid = session('uid');
    $roleid = session('roleid');
    foreach ($menu_list as $key => $value) {
        $child = db('menu')->field('`id`,`name`,`m`,`c`,`a`,`data`,icon')->where(array('parentid' => $value['id'], 'display' => '1'))->order('listorder ASC')->select();
        foreach ($child as $k => $v) {
            if ($uid != 1) {
                $data = db('auth_role_priv')->field('roleid')->where(array('roleid' => $roleid, 'm' => $v['m'], 'c' => $v['c'], 'a' => $v['a']))->find();
                if (!$data) {
                    unset($child[$k]);
                }
            }
        }
        if ($child) {
            $menu_list[$key]['child'] = $child;
        } else {
            unset($menu_list[$key]);
        }
    }
    return $menu_list;
}

/**
 * 设置路由映射
 */
function set_mapping() {
    if (!$mapping = cache('mapping')) {
        $data = db('category')->field('type,catid,catdir')->where('type!="2"')->select();
        $mapping = array();
        foreach ($data as $val) {
            $mapping['^' . $val['catdir'] . '$'] = 'home/index/lists/catid/' . $val['catid'];
            if (!$val['type']) {
                $mapping['^' . $val['catdir'] . '\/list_(\d+)$'] = 'home/index/lists/catid/' . $val['catid'] . '/page/$1';
                $mapping['^' . $val['catdir'] . '\/(\d+)$'] = 'home/index/show/catid/' . $val['catid'] . '/id/$1';
            }
        }
        //结合自定义URL规则
        $route_rules = get_urlrule();
        if (!empty($route_rules))
            $mapping = array_merge($route_rules, $mapping);
        cache('mapping', $mapping);
    }
    return $mapping;
}

/**
 * 获取自定义URL规则
 * @return array
 */
function get_urlrule() {
    if (!$urlrule = cache('urlrule')) {
        $data = db('urlrule')->select();
        $urlrule = array();
        foreach ($data as $val) {
            $val['urlrule'] = '^' . str_replace('/', '\/', $val['urlrule']) . '$';
            $urlrule[$val['urlrule']] = $val['route'];
        }
        cache('urlrule', $urlrule);
    }
    return $urlrule;
}

/**
 * 发送邮件    必须做好配置邮箱
 * @param $email    收件人邮箱
 * @param $title    邮件标题
 * @param $content     邮件内容
 * @param $mailtype    邮件内容类型
 * @return true or false
 */
function sendmail($email, $title = '', $content = '', $mailtype = 'HTML') {
    $mail_pass = get_config('mail_pass');
    if (!is_email($email) || empty($mail_pass))
        return false;
    $smtp = new \class_smtp(get_config('mail_server'), get_config('mail_port'), get_config('mail_auth'), get_config('mail_user'), get_config('mail_pass'));
    $state = $smtp->sendmail($email, get_config('mail_from'), $title . ' - ' . get_config('webname'), $content, $mailtype);
    if (!$state)
        return false;
    return true;
}

/**
 * 获取用户头像
 * @param $uid
 * @param $size    big, middle, small
 * @param $type     real,_real
 * @return string
 */
function get_avatar($uid, $size = 'middle', $type = '') {
    $size = in_array($size, array('big', 'middle', 'small')) ? $size : 'middle';
    $uid = abs(intval($uid));
    $uid = sprintf("%09d", $uid);
    $dir1 = substr($uid, 0, 3);
    $dir2 = substr($uid, 3, 2);
    $dir3 = substr($uid, 5, 2);
    $typeadd = $type == 'real' ? '_real' : '';
    return $dir1 . '/' . $dir2 . '/' . $dir3 . '/' . substr($uid, -2) . $typeadd . "_avatar_$size.jpg";
}
